package com.lagou.educourseboot.controller;



import com.lagou.educourseboot.entity.Course;
import com.lagou.educourseboot.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@RestController
@RequestMapping("/course")
@CrossOrigin //解决跨域问题
public class CourseController {

    @Autowired
    private CourseService courseService;

    @GetMapping("getAllCourse")
    public List<Course> getAllCourse(){
        //模拟多线程：创建一个容量20个的线程池模拟缓存穿透现象
        ExecutorService es = Executors.newFixedThreadPool(20);
        for (int i= 1; i <= 20; i++){
            //提交线程
            es.submit(new Runnable() {
                @Override
                public void run() {
                    courseService.getAllCourse();
                }
            });
        }

        List<Course> list = courseService.getAllCourse();
       return list;
   }


    @GetMapping("getCourseById/{courseid}")
    public Course getCourseById(@PathVariable("courseid") Integer courseid){
       return courseService.getCourseById(courseid);
   }

    @GetMapping("getMyCoursesById/{ids}")
    public List<Course> getMyCoursesById(String ids){
        System.out.println("带查询的课程id:" + ids);

        List<String> idList = new ArrayList<>();
        String id = null;
        while(ids.indexOf("=")>0) {
            if (ids.indexOf("&") > 0) {
                id = ids.substring(ids.indexOf("=") + 1, ids.indexOf("&"));
                System.out.println(id);
                ids = ids.substring(ids.indexOf("&")+1);
            } else {
                id = ids.substring(ids.indexOf("=") + 1);
                System.out.println(id);
                ids = ids.substring(ids.indexOf("=")+1);
            }
            idList.add(id);
        }
        System.out.println(idList);  //[7, 9]

        List<Course> list = courseService.getMyCoursesById(idList);
        return list;
    }

}
